import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../provider/post_list_provider.dart';
import '../widgets/like_button.dart';

class PostGridView extends StatefulWidget {
  const PostGridView({super.key});

  @override
  State<PostGridView> createState() => _PostGridViewState();
}

class _PostGridViewState extends State<PostGridView> {
  final ScrollController _scrollController = ScrollController();

  static const String defaultImage =
      'https://images.unsplash.com/photo-1506377247377-2a5b3b417ebb?w=800';

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<PostListProvider>(context, listen: false).fetchPosts();
    });
    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    final provider = Provider.of<PostListProvider>(context, listen: false);
    if (_scrollController.position.pixels >=
            _scrollController.position.maxScrollExtent - 200 &&
        !provider.isLoading &&
        provider.hasMore) {
      provider.fetchPosts();
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  double getImageHeightByIndex(int index) => 180 + (index % 3) * 20;

  Widget buildPostCard(Map<String, dynamic> post, int index) {
    final images = post['images'] != null
        ? List<String>.from(jsonDecode(post['images']))
        : <String>[];
    final imageUrl = images.isNotEmpty ? images[0] : defaultImage;
    final imageHeight = getImageHeightByIndex(index);

    return GestureDetector(
      onTap: () {
        context.pushNamed(
          'postDetail',
          pathParameters: {'id': post['id'].toString()},
        );
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 2,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        clipBehavior: Clip.antiAlias,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CachedNetworkImage(
              imageUrl: imageUrl,
              height: imageHeight,
              width: double.infinity,
              fit: BoxFit.cover,
              placeholder: (context, url) => Container(
                color: Colors.grey[200],
                height: imageHeight,
                width: double.infinity,
              ),
              errorWidget: (context, url, error) => const Icon(Icons.error),
              fadeInDuration: const Duration(milliseconds: 300),
              fadeInCurve: Curves.easeIn,
            ),
            Padding(
              padding: const EdgeInsets.all(4),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    post['title'] ?? '',
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 14,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 2),
                  Text(
                    post['content'] ?? '',
                    style: const TextStyle(fontSize: 12, color: Colors.black54),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 8),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          CircleAvatar(
                            radius: 12,
                            backgroundImage: NetworkImage(
                              post['avatar'] ??
                                  'https://sns-avatar-qc.xhscdn.com/avatar/1040g2jo31b4110cl7e0047dgusldddtn5dp6fco',
                            ),
                          ),
                          const SizedBox(width: 6),
                          Text(
                            post['username'] ?? '',
                            style: const TextStyle(
                              fontSize: 12,
                              color: Colors.black54,
                            ),
                          ),
                        ],
                      ),
                      LikeButton(postId: post['id'].toString()),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 交叉淡入淡出动画（旧组件淡出 + 新组件淡入）
  Widget _fadeTransitionBuilder(Widget child, Animation<double> animation) {
    return FadeTransition(opacity: animation, child: child);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<PostListProvider>(
      builder: (context, provider, _) {
        final isEmptyLoading = provider.posts.isEmpty && provider.isLoading;

        return AnimatedSwitcher(
          duration: const Duration(milliseconds: 400),
          switchInCurve: Curves.easeInOut,
          switchOutCurve: Curves.easeInOut,
          transitionBuilder: (child, animation) {
            // 旧组件淡出，新组件淡入，交叉渐变
            final fadeIn = CurvedAnimation(
              parent: animation,
              curve: Curves.easeIn,
            );
            final fadeOut = ReverseAnimation(fadeIn);
            if (child.key == const ValueKey('loading_placeholder')) {
              // loading 留白淡入淡出
              return FadeTransition(opacity: fadeIn, child: child);
            } else {
              // 内容列表淡入淡出
              return FadeTransition(opacity: fadeIn, child: child);
            }
          },
          child: isEmptyLoading
              ? Container(
                  key: const ValueKey('loading_placeholder'),
                  color: Colors.white,
                  height: MediaQuery.of(context).size.height - kToolbarHeight,
                  width: double.infinity,
                )
              : RefreshIndicator(
                  key: const ValueKey('post_list'),
                  onRefresh: () async => provider.fetchPosts(reset: true),
                  child: MasonryGridView.count(
                    controller: _scrollController,
                    crossAxisCount: 2,
                    mainAxisSpacing: 1,
                    crossAxisSpacing: 1,
                    padding: const EdgeInsets.all(6),
                    itemCount:
                        provider.posts.length + (provider.hasMore ? 1 : 0),
                    itemBuilder: (context, index) {
                      if (index == provider.posts.length) {
                        return const Center(
                          child: Padding(
                            padding: EdgeInsets.symmetric(vertical: 8),
                            child: CircularProgressIndicator(),
                          ),
                        );
                      }
                      return buildPostCard(provider.posts[index], index);
                    },
                  ),
                ),
        );
      },
    );
  }
}
